import Taro, {Component, Config} from '@tarojs/taro'
import {View, Button, Text, Swiper, SwiperItem, Image, ScrollView, Input, Picker, Form} from '@tarojs/components'
import {inject, observer} from '@tarojs/mobx'
import {
  userInfoInterface,
  navigateTo,
  getUserInfo,
  phonePartOf,
  showToast, navigateBack, updateUserInfo
} from "../../utils/common";
import SmsCode from "../../components/SmsCode";


import {IStoreProps} from '../../store/Stores'
import './editPhone.scss'

interface IHomeProps extends IStoreProps {
}

@inject("stores")
@observer
class EditPhone extends Component<IHomeProps> {
  constructor(props) {
    super(props)
  }

  state = {
    userInfo: {} as userInfoInterface,
    smsCode:'',
    phoneNumber: '',
    codeState: 0, // 0是绑定， 1是修改
  }

  componentWillMount() {
    let userInfo = getUserInfo()
    let codeState = this.$router.params.id || 0
    this.setState({ userInfo, codeState })
  }

  link = (url: string = '/pages/index/index'): void => {
    navigateTo(url)
  }

  getCode(phoneNumber: string, code: string) {
    this.setState({ phoneNumber, smsCode: code })
  }

  submit() {
    let { smsCode, phoneNumber, codeState } = this.state
    if(!phoneNumber || !smsCode) { showToast('请填写手机号或手机验证码~'); return }
    let { userStore } = this.props.stores
    userStore.setUserPhoneAsync({
      form: { smsCode, phoneNumber, codeState },
      callback: () => {
        if(codeState === 0) {
          showToast('手机绑定成功~')
        }else {
          showToast('手机修改成功~')
        }
        // 更新用户缓存信息
        updateUserInfo('userPhone', phoneNumber)
        setTimeout(() => { navigateBack() }, 2000)
      }
    })
  }

  render() {
    let { userInfo } = this.state
    return (
      <View className='page-bg content-20'>
        {
          userInfo.userPhone&&  <View className='desc current-phone'>当前手机号： {phonePartOf(userInfo.userPhone)}</View>
        }
        <Form onSubmit={this.submit.bind(this)}>
         <View className='form-body'>
           <SmsCode filedName='新手机号码' onGetCode={this.getCode.bind(this)} />
         </View>
          <Button className='circular-submit' formType='submit'>确定更换</Button>
        </Form>
      </View>
    )
  }
}

export default EditPhone

